package com.smarthome.api.mobile.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smarthome.common.mobile.Service;
import com.smarthome.common.tools.APIUtil;
import com.smarthome.core.account.AccountDoorService;
import com.smarthome.core.deviceManager.EquipmentDevCameraService;
import com.smarthome.core.deviceManager.EquipmentDevSwingService;
import com.smarthome.core.deviceManager.EquipmentDevTalkService;
import com.smarthome.core.deviceManager.EquipmentUserService;
import com.smarthome.domain.bean.ShAccountDoor;
import com.smarthome.domain.bean.ShEquipmentDevCamera;
import com.smarthome.domain.bean.ShEquipmentDevSwing;
import com.smarthome.domain.bean.ShEquipmentDevTalk;
import com.smarthome.domain.bean.ShEquipmentUser;
import com.smarthome.domain.enums.AccountDoorStatus;
import com.smarthome.domain.enums.EquipmentTypeEnum;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileUserDeviceInfoRequest;
import com.smarthome.domain.vo.api.UserDeviceBean;


/**
 * 得到登录用户的授权的设备信息
 * @author szc
 * @since 2015-10-16
 *
 */
@org.springframework.stereotype.Service("mobile.userDeviceIndo.service")
public class MobileUserDeviceInfoService implements Service<MobileResponse<?>>{

	@Resource
    private EquipmentUserService equipmentUserService;
	
	@Resource
	private EquipmentDevSwingService equipmentDevSwingService;
	
	@Resource
	private EquipmentDevTalkService equipmentDevTalkService;
	
	@Resource
	private EquipmentDevCameraService equipmentDevCameraService;
	
	@Resource
    private AccountDoorService accountDoorService;
	
	/**
	 * 获取用户当前小区的所有摆闸
	 * @param request
	 * @param response
	 */
	public void getResidenceSwing(MobileUserDeviceInfoRequest request, MobileResponse<List<Map<String, Object>>> response){
		Long residenceId = request.getAccount().getResidenceId();
		ShEquipmentDevSwing swing = new ShEquipmentDevSwing();
		swing.setResidenceId(residenceId);
		swing.setStatus(1);//可用
		
		List<ShEquipmentDevSwing> swings = equipmentDevSwingService.getAllList(swing);
		List<Map<String, Object>> data = groupData(swings);
		response.setData(data);
	}
	
	/**
	 * 获取用户当前小区所有房屋的单元门口机设备
	 * @param request
	 * @param response
	 */
	public void getUnitTalk(MobileUserDeviceInfoRequest request, MobileResponse<List<ShEquipmentDevTalk>> response){
		ShAccountDoor accountDoor = new ShAccountDoor();
        accountDoor.setAccountId(request.getAccountId());
        accountDoor.setStatus(AccountDoorStatus.OK.getType());//审核通过的房屋
        accountDoor.setResidenceId(request.getAccount().getResidenceId());//当前小区
        
        List<ShAccountDoor> accountDoors = accountDoorService.queryDataListByCondition(accountDoor);
        Set<Long> unitIds = new HashSet<Long>();
        for(ShAccountDoor acDoor : accountDoors){
        	unitIds.add(acDoor.getUnitId());
        }
        Long[] arrs = new Long[unitIds.size()];
        List<ShEquipmentDevTalk> talks = equipmentDevTalkService.getByBuildingIds(unitIds.toArray(arrs));
        response.setData(talks);
	}
	
	/**
	 * 获取用户当前小区的所有监控
	 * @param request
	 * @param response
	 */
	public void getResidenceCamera(MobileUserDeviceInfoRequest request, MobileResponse<List<ShEquipmentDevCamera>> response){
		Long residenceId = request.getAccount().getResidenceId();
		ShEquipmentDevCamera camera = new ShEquipmentDevCamera();
		camera.setResidenceId(residenceId);
		camera.setStatus(1);//在线设备
		
		List<ShEquipmentDevCamera> cameras = equipmentDevCameraService.getAllList(camera);
		for(ShEquipmentDevCamera camer : cameras){
			String sdkParam = camer.getSdkParam();
			try{
				JSONObject data = JSONObject.parseObject(sdkParam);
				JSONArray arr = data.getJSONObject("result").getJSONArray("data");
				
				camer.setSdk(JSONObject.parseObject(arr.get(0).toString()));
				camer.setSdkParam("");
			}catch(Exception e){
				e.printStackTrace();
				continue;
			}
		}
		response.setData(cameras);
	}
	
	/**
	 * 得到用户的设备设备信息
	 * @param request
	 * @param response
	 * 请求地址
	 * http://127.0.0.1:8080/mobile/gateway.do?body={"service":"mobile.userDeviceIndo.service","method":"getUserDeviceMJList","deviceId":1,"user_id":123}
	 */
	 public void getUserDeviceMJList(MobileUserDeviceInfoRequest request, MobileResponse< Object> response) {
		 Long user_id = request.getAccountId();						//用户id
		 Long residenceId =request.getAccount().getResidenceId();	//小区id
		 String do_type = request.getDo_type();
		 if(user_id ==null){
			 MobileCodeEnum.DEVICE_MSG.getCustomEnum("未得到用户信息");
			 return;
		 }
		 if(residenceId ==null){
			 MobileCodeEnum.DEVICE_MSG.getCustomEnum("未得到登录用户所属小区");
			 return;
		 }
		 if(org.apache.commons.lang.StringUtils.isBlank(do_type)){
			 MobileCodeEnum.DEVICE_MSG.getCustomEnum("未得到登录用户操作类型");
			 return;
		 }
		 
		List<UserDeviceBean> userDevArryList= new ArrayList<UserDeviceBean>();
		HashMap params = new  HashMap<String, Object>();  
	    params.put("user_id", user_id);					//登录用户id
	    params.put("residence_id", residenceId);		//用户所属小区id
	    params.put("type_code", do_type);				//获取设备类型: mj：门禁;bz：摆闸
	    params.put("device_state", "1");				//设备状态1：已入:2：已出：3：已删除
		 List<UserDeviceBean> userDevList =equipmentUserService.queryUserDeviceBeanList(params);
		 List<UserDeviceBean> onlyDevAdsList  = new ArrayList<UserDeviceBean>();
		 JSONObject obj_all =new JSONObject();
		 JSONArray arry_all = new JSONArray();
		 if(userDevList!=null && userDevList.size()>0){
			 /*for(Iterator it=userDevList.iterator(); it.hasNext();) {  
		            //List里存放的是java.util.Map类型  
		            Object obj = (Object)it.next();  
		            System.out.println(obj.getClass());  
		            System.out.println(obj);  
		        }*/
			 for (int i = 0; i < userDevList.size(); i++) {
				   Map map = (Map) userDevList.get(i);
				   String id = String.valueOf(map.get("id"));						//sh_equipment_user表主键id
				   String useId = String.valueOf(map.get("user_id"));				//sh_account表主键id
				   String residence_id = String.valueOf(map.get("residence_id"));	//小区id
				   String building_id = String.valueOf(map.get("building_id"));		//楼栋id
				   String building_unit_id = String.valueOf(map.get("building_unit_id"));//单元id
				   String door_id = String.valueOf(map.get("door_id"));					//门牌id
				   String address = String.valueOf(map.get("dev_ads"));					//设备地址
				   String bing_type = String.valueOf(map.get("bing_type"));				//设备绑定类型：1：设备与用户关联绑定；2：设与小区绑定
				   String comm_type = String.valueOf(map.get("comm_type"));				//通信类型：1开门；2：关门；3：可视对讲；4：视频预览；5:视频历史
				   String dev_id = String.valueOf(map.get("dev_id"));					//sh_equipment_info表主键：设备id
				   String dev_name = String.valueOf(map.get("name"));					//设备名称
				   String dev_ip = String.valueOf(map.get("device_ip"));				//设备ip地址
				   String dev_mac = String.valueOf(map.get("device_mac"));				//设备mac地址
				   String dev_num = String.valueOf(map.get("self_code"));				//设备序号
				   String device_state = String.valueOf(map.get("device_state"));		//设备状态1：已入:2：已出：3：已删除
				   String dev_type_code = String.valueOf(map.get("equipment_type_code"));	//设备类型唯一编码
				   String dev_type_id = String.valueOf(map.get("equipment_type_id"));		//设备类型id
				   String is_main_dev = String.valueOf(map.get("is_main_dev"));//是否主设备 1:主设备；2:子设备
				   String p_devId = String.valueOf(map.get("parentDevId"));//上级设备id

				   UserDeviceBean userDeviceBeanList = new UserDeviceBean();
				   userDeviceBeanList.setDev_id(dev_id);
				   userDeviceBeanList.setDev_address(address);
				   userDeviceBeanList.setDev_name(dev_name);
				   userDeviceBeanList.setDev_ip(dev_ip);
				   userDeviceBeanList.setDev_mac(dev_mac);
				   userDeviceBeanList.setDev_num(dev_num);
				   userDeviceBeanList.setComm_type(comm_type);
				   userDeviceBeanList.setDev_typeCode(dev_type_code);
				   if(StringUtils.isNotBlank(dev_type_code)){
					   if(dev_type_code.equals(EquipmentTypeEnum.DEV_TALK.getCode())){
						   userDeviceBeanList.setDev_typeName("门禁");
					   }
					   if(dev_type_code.equals(EquipmentTypeEnum.DEV_SWING.getCode())){
						   userDeviceBeanList.setDev_typeName("摆闸");
					   }
					   if(dev_type_code.equals(EquipmentTypeEnum.DEV_TALK.getCode())){
						   userDeviceBeanList.setDev_typeName("门口机");
					   }
				   }else{
					   userDeviceBeanList.setDev_typeName(""); 
				   }
				   userDevArryList.add(userDeviceBeanList);
				   onlyDevAdsList.add(userDeviceBeanList);
			}
			 
			 //去掉重复的数据
			 for( int i = 0 ; i < onlyDevAdsList.size() - 1 ; i ++ ) {  
				 for( int j = onlyDevAdsList.size() - 1 ; j > i; j -- ) {  
				    if(onlyDevAdsList.get(j).getDev_address().toString().equals(onlyDevAdsList.get(i).getDev_address().toString())) {  
				    	onlyDevAdsList.remove(j);  
				    }   
				}   
			}
			 
			 if(onlyDevAdsList!=null && onlyDevAdsList.size()>0){
				 for( int i = 0 ; i < onlyDevAdsList.size()  ; i ++ ) {
					 JSONObject obj = new JSONObject();
					 JSONArray arry = new JSONArray();
					 for( int m = 0 ; m < userDevArryList.size()  ; m ++ ) {  
						 if(onlyDevAdsList.get(i).getDev_address().toString().equals(userDevArryList.get(m).getDev_address().toString())) {  
							 arry.add(userDevArryList.get(m));
						 } 
					 }
					 obj.put("dev_list", arry) ;
					 if(onlyDevAdsList.get(i).getDev_address()!=null && !onlyDevAdsList.get(i).getDev_address().equals("") && !onlyDevAdsList.get(i).getDev_address().equals("null")){
						 obj.put("dev_address", onlyDevAdsList.get(i).getDev_address().toString());
					 }else{
						 obj.put("dev_address", "未知位置");
					 }
					 arry_all.add(obj);
					// System.out.println(obj.toJSONString());
				 }
			 }
		 }
		 obj_all.put("dev_info", arry_all);
		 response.setData(obj_all);
	 }
	 
	 private List<Map<String, Object>> groupData(List<ShEquipmentDevSwing> swings){
		 Map<String,List<ShEquipmentDevSwing>> res = new HashMap<String, List<ShEquipmentDevSwing>>();
		 
		 //数据分祖
		 for(ShEquipmentDevSwing swing : swings){
			 List<ShEquipmentDevSwing> data = res.get(swing.getDoorName());
			 if(null == data){
				 data = new ArrayList<ShEquipmentDevSwing>();
				 data.add(swing);
			 }else{
				 data.add(swing);
			 }
			 res.put(swing.getDoorName(), data);
		 }
		 
		 //组装数据
		 List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		 for (String key : res.keySet()) {
	            Map<String, Object> map = new HashMap<String, Object>();
	            map.put("doorName", key);
	            map.put("talks", res.get(key));
	            datas.add(map);
	        }
		 return datas;
	 }
}
